#include <mm32f0120.h>
#include <stdio.h>
#include "MM_SERVO_PWM.h"


volatile uint32_t TIM3_CC_InterruptFlag;
volatile uint32_t TIM3_CC_Value1;
volatile uint32_t TIM3_CC_Value2;


void SERVO_PWM_Init(void)
{	
    GPIO_InitTypeDef        GPIO_InitStruct;
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
	TIM_OCInitTypeDef TIM_OCInitStruct;
	
	
	RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);

    GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_3);    /* TIM3_CH1 */

    GPIO_StructInit(&GPIO_InitStruct);
    GPIO_InitStruct.GPIO_Pin   = GPIO_Pin_4;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_High;
    GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_FLOATING;
    GPIO_Init(GPIOB, &GPIO_InitStruct);

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

    TIM_TimeBaseStructInit(&TIM_TimeBaseInitStruct);
    TIM_TimeBaseInitStruct.TIM_Prescaler         = 72 - 1;
    TIM_TimeBaseInitStruct.TIM_CounterMode       = TIM_CounterMode_Up;
    TIM_TimeBaseInitStruct.TIM_Period            = 20000 - 1;
    TIM_TimeBaseInitStruct.TIM_ClockDivision     = TIM_CKD_Div1;
    TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);

    TIM_OCStructInit(&TIM_OCInitStruct);
    TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
	TIM_OCInitStruct.TIM_Pulse = 0;
    TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
    TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OC3Init(TIM3, &TIM_OCInitStruct);

    TIM_Cmd(TIM3, ENABLE);
	TIM_CtrlPWMOutputs(TIM3, ENABLE);
	
	
}


void SERVO_PWM_SetCompare(uint16_t angle)
{
	/*
		0.5ms对应占空比：0.5ms / 20ms = 2.5% → CCR值为 (32768 / 50) * 0.025 ≈ 16.4。
		2.5ms对应占空比：2.5ms / 20ms = 12.5% → CCR值为 (32768 / 50) * 0.125 ≈ 81.9。
	*/
	// uint16_t compare = 16 + (angle * (81 - 16)) / 180;  // 线性映射0°~180°到16~81
	// uint16_t compare = 50 + (angle * (250 - 50)) / 180; // 映射0°~180°到50~250
	uint16_t compare = 500 + (angle * (2500 - 500)) / 180; // 映射 0°~180° 到 500~2500
	// uint16_t compare = 50 + (angle * 10); // 0.5ms~2.5ms（50~250@1kHz）
	printf("%d", compare);
    TIM_SetCompare3(TIM3, compare);
}